package com.gimi.cloud.jimi.commonService.common.impl;

import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.commonService.common.JmConfigService;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Created by shazhiwei on 2018/1/10.
 */
@Service
public class JmConfigServiceImpl implements JmConfigService {
    private final IRedisService redisService;
    private final SysConfigDao configDao;
    private static final Logger logger = LoggerFactory.getLogger(JmConfigServiceImpl.class);

    public JmConfigServiceImpl(IRedisService redisService,SysConfigDao configDao){
        this.redisService = redisService;
        this.configDao = configDao;
    }

    @Override
    public String getValueByKey(String key) {
        String result = getFromRedis(key);
        if(StringUtil.isBlank(result)){
            result = configDao.getConfigByKey(key);
            if(!StringUtil.isBlank(result)){
                logger.info(String.format("===>从mysql获取配置%s：%s",key,result));
                setDataToRedis(key,result);
            }
        }else{
            logger.info(String.format("===>从redis获取配置%s：%s",key,result));
        }
        return result;
    }

    /**
     * 从redis获取配置值
     * @param key
     * @return
     */
    private String getFromRedis(String key){
        String result = null;
        try{
            String redisKey = RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + key;
            result = redisService.get(redisKey);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    private void setDataToRedis(String key,String value){
        try{
            String redisKey = RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + key;
            redisService.set(redisKey,value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
